package logic

import (
	"context"
	"fmt"
	"login-reg/cache"
	"login-reg/model"

	"login-reg/loginrpc/internal/svc"
	"login-reg/loginrpc/loginrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *loginrpc.LoginRequest) (*loginrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user model.User
	model.DB.Where("account=?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("用户未注册请去注册")
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码错误")
	}
	result, _ := cache.Rdb.Get(cache.Ctx, "SenSms"+in.Account).Result()
	if result != in.SenSmsCode {
		return nil, fmt.Errorf("短信验证失败")
	}
	cache, _ := cache.Rdb.Get(cache.Ctx, "captcha"+in.Account).Result()
	if cache != in.CaptchaCode {
		return nil, fmt.Errorf("图片验证失败")
	}
	return &loginrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
